﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using ServerListerner.Enums;

namespace ServerListerner.Helper
{
    public static class NetHelperEvent
    {
        public static bool PortInUse(this int port,bool IsTCP=true)
        {
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = IsTCP?ipProperties.GetActiveTcpListeners():ipProperties.GetActiveUdpListeners();
            return ipEndPoints.Where(s => s.Port == port).Any();
        }
        public static bool IsPort(this int port)
        {
            if (port <= 0 || port >= 65535)
                return false;
            return true;
        }
        public static bool IsIP(this string ip)
        {
            if (ip.Any(char.IsLetter))
                return false;
            int[] arr = Array.ConvertAll<string, int>(ip.Split('.'), s => Convert.ToInt32(s));
            if (arr.Length != 4)
                return false;
            return  arr.Where(s=>s<=0||s>255).Any()?false:true;
        }
        public static IPAddress StrToIPAddress(this string ip)
        { 
            if (ip.IsIP())
                return IPAddress.Parse(ip);
            return IPAddress.None;
        }
    }
}
